import utilAxios from '@/util/util-axios'

const context = {}

async function init(route, form = {}) {
    const models = route.path.split('/')
    try {
        let ruleInit = require(`@/views/modular-rule/${models[1]}/${models[2]}/rule.js`).init
        context.rule = await ruleInit(form)
    } catch (e) {
        console.log(route.meta.title + '模块异常 - ', e)
        context.rule = {}
    }
    context.api = utilAxios.initBaseApi(models[1], models[2])
    await initAttributes(context)
    return context
}

function initRule(attribute) {
    context.rule.tableConfig = context.rule.tableConfig || {}
    context.rule.formConfig = context.rule.formConfig || {}
    initTableConfigRule(context.rule.tableConfig, attribute)
    initTableConfigRule(context.rule.formConfig, attribute)
}

function initTableConfigRule(attrConfig, attribute) {
    attrConfig[attribute.name] = { ...attribute, ...attrConfig[attribute.name]  }
}

async function initAttributes(context) {
    context.attributes = await context.api.getAttributes()
    for (const attribute of context.attributes) {
        if (attribute.type === 6 || attribute.type === 61) {
            let res = await utilAxios.initBaseApi(attribute.oneModular, attribute.twoModular).list({ limit: 999 })
            attribute.dictList = (res.records || res.records).map(item => {
                return { name: item.name, val: item.id }
            })
        }
        initRule(attribute)
    }
}

export default {
    init
}
